package cn.tworice.common.util;

import javax.servlet.http.HttpServletRequest;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class NetworkUtil {
    public static String getWlanMAC() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();

                // 确保网络接口是无线网络接口（WLAN）
                if (networkInterface.isUp() && networkInterface.supportsMulticast() && !networkInterface.isLoopback()) {
                    byte[] macAddressBytes = networkInterface.getHardwareAddress();

                    if (macAddressBytes != null) {
                        StringBuilder macAddress = new StringBuilder();
                        for (int i = 0; i < macAddressBytes.length; i++) {
                            macAddress.append(String.format("%02X", macAddressBytes[i]));
                            if (i < macAddressBytes.length - 1) {
                                macAddress.append(":");
                            }
                        }
                        return macAddress.toString();
                    } else {
                        throw new RuntimeException("无法获取WLAN的MAC地址。");
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();

        }
        return null;
    }

    /**
     * 获取客户端真实IP（适配代理场景）
     */
    public static String getClientIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.split(",")[0].trim();
    }
}
